import asyncio
import time

from bleak import BleakScanner, BleakClient


# 扫描附近的 BLE 设备
async def scan_devices(service_uuids: list[str]):
    devices = await BleakScanner.discover(timeout=20, return_adv=True,
                                          service_uuids=service_uuids)
    for address in devices:
        item = devices[address]
        advertisement_data = item[1]
        device_name = advertisement_data.local_name if advertisement_data.local_name else "未知设备"
        if advertisement_data.local_name:
            print(f"MAC: {address:<17} 设备名称: {device_name:<32} \t 信号强度: {advertisement_data.rssi:>5}")


def print_service_and_characteristic(client: BleakClient):
    """
    打印服务和特征
    """
    services = client.services
    for service in services:
        print(f"服务名称: {service.description} 服务uuid: {service.uuid}")
        for characteristic in service.characteristics:
            print(
                f"\t特征值uuid: {characteristic.uuid} 特征值描述: {characteristic.description} 特征值属性: {characteristic.properties}")
    print("---" * 30)


def disconnected_callback(client: BleakClient):
    print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 设备断开连接 {client.address}")


if __name__ == "__main__":
    # 心率服务
    # 0000180d-0000-1000-8000-00805f9b34fb
    # 姿态服务
    # 0000ffe5-0000-1000-8000-00805f9a34fb
    asyncio.run(scan_devices(['0000180d-0000-1000-8000-00805f9b34fb', '0000ffe5-0000-1000-8000-00805f9a34fb']))
    # asyncio.run(scan_devices([]))
